//
//  BroadcastGeneralViewController.m
//  xiaoyiNew
//
//  Created by TW on 2017/2/5.
//  Copyright © 2017年 讯一. All rights reserved.
//

#import "BroadcastGeneralViewController.h"
#import "BroadcastTableViewCell.h"
#import "SubjectDetailsViewController.h"
#import "XMCenter.h"
#import "XMNetworking.h"
#import "NSString+GetBaseURL.h"
#import "BroadcastModel.h"
#import "MJExtension.h"
#import "BeansViewController.h"

@interface BroadcastGeneralViewController ()<UITableViewDelegate, UITableViewDataSource, BroadcastTableViewCellDelegate> {

    NSArray * _headerTitle;
    BarodcastType _type;
    NSString * _url;
}
@property(nonatomic, strong) UITableView * tableView;//
@property(nonatomic, strong) UIScrollView * headerView;//头视图
@property(nonatomic, strong) NSArray<BroadcastModel *> * modelArr;//数据源

@end

@implementation BroadcastGeneralViewController

- (instancetype)initWithType:(BarodcastType)type url:(NSString *)url
{
    self = [super init];
    if (self) {
        _type = type;
        _url = url;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = TSColor(236, 236, 236);
    [self initializeDataSource];
    [self initializeUserInterface];
    [self initializeConstraints];
    // Do any additional setup after loading the view.
}


- (void)initializeDataSource {
    //更新数据
    _headerTitle = @[@"全部", @"逛吃", @"达人", @"美妆", @"宅男", @"腐女", @"招领"];
    [self networkingWithUrl:_url fenleiname:@""];
}
- (void)initializeUserInterface {
    //初始化界面
    [self.view addSubview:self.tableView];
    
}
- (void)initializeConstraints {
    //设置约束
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(44);
        make.left.right.equalTo(self.view);
        make.bottom.equalTo(self.view).offset(-49);
    }];
}

#pragma mark - action -
- (void)networkingWithUrl:(NSString *)url fenleiname:(NSString *)fenleiname{
    
    __weak typeof(self) weakself = self;
    [XMCenter sendRequest:^(XMRequest * _Nonnull request) {
        request.url = [NSString getURLWithSubURL:url];
        if (_type == SchoolBarodcastType) {
            
            request.parameters = @{@"ctype":@"重庆大学",@"tops":@"0",@"fenleiname":fenleiname};
        }else {
        
            request.parameters = @{@"ctype":@"重庆大学",@"tops":@"0",@"userid":@"245"};
        }
        request.responseSerializerType = kXMResponseSerializerRAW;
        request.httpMethod = kXMHTTPMethodPOST;
    } onSuccess:^(id  _Nullable responseObject) {
        id jsonObject = [NSJSONSerialization
                         JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments
                         error:nil];
        NSArray * arr = (NSArray *)jsonObject;
        weakself.modelArr = [BroadcastModel mj_objectArrayWithKeyValuesArray:arr];
        if (arr.count>2) {
            NSLog(@"%@",arr[1]);

        }
        [BroadcastModel replacedKeyFromPropertyName];
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakself.tableView reloadData];
        });
        
    } onFailure:^(NSError * _Nullable error) {
        NSLog(@"%@", [error localizedDescription]);
    }];
}
#pragma mark - 点击 -
//点击
- (void)action_classifyClick:(UIButton *)sender {
    
    NSString * fenleiname = @"";
    if (sender.tag - 300 == 0) {
        fenleiname = @"";
    }else {
    
         fenleiname = _headerTitle[sender.tag - 300];
    }
    [self networkingWithUrl:@"GetXiaoyiXiaoneiComments" fenleiname:fenleiname];
    NSLog(@"分类");
}

#pragma mark - BroadcastTableViewCellDelegate -
- (void)cellFuncClickWitnIndex:(NSInteger)index indexPath:(NSIndexPath *)indexPath{

    switch (index) {
        case 0:{
            //点赞
            NSLog(@"点赞");
        }
            break;
        case 1:{
            //消息
            NSLog(@"消息");
            self.navigationController.navigationBar.hidden = NO;
            self.tabBarController.tabBar.hidden = YES;
            SubjectDetailsViewController * detailsVC = [[SubjectDetailsViewController alloc] init];
            detailsVC.model = self.modelArr[indexPath.row];
            [self.navigationController pushViewController:detailsVC animated:YES];
            
        }
            break;
        case 2:{
            //分享
            NSLog(@"分享");
        }
            break;
        case 3:{
            //撒豆
            NSLog(@"撒豆");
            self.navigationController.navigationBar.hidden = NO;
            self.tabBarController.tabBar.hidden = YES;
            BeansViewController * beansVC = [[BeansViewController alloc] init];
            [self.navigationController pushViewController:beansVC animated:YES];
        }
            break;
        default:
            break;
    }

}

#pragma mark - UITableViewDelegate, UITableViewDataSource -

//行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.modelArr.count;
}
//高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSArray * images = [self.modelArr[indexPath.row].imageurl componentsSeparatedByString:@"|"];
    NSMutableArray * mArr = [NSMutableArray array];
    for (NSString * str in images) {
        if (str.length > 0) {
            [mArr addObject:str];
        }
    }
    NSInteger page;
    if (mArr.count == 0) {
        page = 0;
    }else if (mArr.count > 0 && mArr.count <=3){
        page = 1;
    }else if (mArr.count > 3 && mArr.count <=6){
    
        page = 2;
    }else {
    
        page = 3;
    }
    return 215 + page*115;
    
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {

    return self.headerView;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {

    if (_type == SchoolBarodcastType) {
        return 45;
    }else {
    
        return 0.0001;
    }
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {

    return 0.00001;
}
//cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    BroadcastTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    cell.model = self.modelArr[indexPath.row];
    cell.delegate = self;
    return cell;
}
//cell点击
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSLog(@"%ld",indexPath.row);
}


#pragma mark - lazy -
- (UITableView *)tableView {

    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, Screen_Width, Screen_Height) style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [_tableView registerNib:[UINib nibWithNibName:@"BroadcastTableViewCell" bundle:nil] forCellReuseIdentifier:@"cell"];
        _tableView.separatorColor = [UIColor clearColor];
        [_tableView setBackgroundColor:[UIColor clearColor]];
    }
    return _tableView;
    
}
- (UIScrollView *)headerView {

    
    if (!_headerView) {
        
        _headerView = [[UIScrollView alloc] init];
        _headerView.showsVerticalScrollIndicator = NO;
        _headerView.showsHorizontalScrollIndicator = NO;
        //添加
        for (int i = 0; i < _headerTitle.count; i ++) {
            UIButton * button = [UIButton buttonWithType:0];
            [button setTitle:_headerTitle[i] forState:0];
            [button setTitleColor:[UIColor blackColor] forState:0];
            button.titleLabel.font = [UIFont systemFontOfSize:15];
            button.tag = 300+i;
            [button addTarget:self action:@selector(action_classifyClick:) forControlEvents:UIControlEventTouchUpInside];
            [_headerView addSubview:button];
            [button mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.equalTo(_headerView);
                make.left.mas_equalTo(i*70 + 10);
                make.size.mas_equalTo(CGSizeMake(40, 40));
            }];
        }
        _headerView.backgroundColor = [UIColor greenColor];
        _headerView.contentSize = CGSizeMake(_headerTitle.count*70 + 10, 0);
    }
    return _headerView;
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
